<?php
/**
 * Created by PhpStorm.
 * User: 雷里雷
 * Date: 2018/12/13
 * Time: 19:53
 */

namespace App\Http\Controllers;

use App\Sentence;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class UsersController extends Controller
{
    public function register(Request $request, User $user)
    {
        $this->validate($request, ['name' => 'max:255|unique:users,name', 'password' => 'min:6']);
        $user->name = $request->name;
        $user->password = Crypt::encrypt($request->password);

        $user->api_token = md5(uniqid());
        $user->save();

        return ['api_token' => $user->api_token];
    }

    public function login(Request $request, User $user)
    {
        $this->validate($request, ['name' => 'max:255|exists:users,name', 'password' => 'min:6']);

        $uncheckedUser = $user->where('name', $request->name)->first();
        if (Crypt::decrypt($uncheckedUser->password) == $request->password) {
            return ['api_token' => $uncheckedUser->api_token];
        } else {
            return ['message' => '密码错误'];
        }
    }

    public function show(User $user, $id)
    {
        return $user->with('sentences')->findOrFail($id);
    }

    public function sentences(Request $request, Sentence $sentence, $id)
    {
        return $sentence->where('user_id', $id)->show($request);
    }
}